package com.xbjtech.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.xbjtech.model.User;
import com.xbjtech.model.beans.Result;
import com.xbjtech.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	UserService userService;
	
	@RequiresPermissions("user:list")
	@GetMapping("/list")
	public String list() {
		return "user/list";
	}
	
	@RequiresPermissions("user:list")
	@GetMapping(value = "/data", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> data(
			@RequestParam(value = "page", required = false, defaultValue = "1")
			int page,
			@RequestParam(value = "rows", required = false, defaultValue = "10")
			int rows
			) {
		PageInfo<User> roles = userService.selectByExamplePage(page, rows, null);
		Map<String, Object> map = new HashMap<>();
		map.put("total", roles.getTotal());
		map.put("rows", roles.getList());
		return map;
	}
	
	@PostMapping("/save")
	@ResponseBody
	public Result save(@Validated User user, Errors errors, Model model) {
		// 服务器端的校验没有做【我建议是要做服务器端的校验】
		// 
		List<FieldError> filedErros = errors.getFieldErrors();
		for (FieldError error : filedErros) {
			model.addAttribute(error.getField() + "ERROR", error.getDefaultMessage());
		}
		try {
			if (null == user.getId()) {
				// 新增
				userService.insertUser(user);
			} else {
				// 修改
				userService.updateByPrimaryKeySelective(user);
			}
//			if (true)
//			throw new RuntimeException();
			// 新增成功 修改成功
			return Result.success();
		} catch (RuntimeException e) {
			// 新增失败 修改失败
			log.error("UserController.save发生了异常=>{}", e.getMessage());
		}
		return Result.fail();
	}
	
	@GetMapping("/del")
	@ResponseBody
	public Result del(
			@RequestParam(required = true)
			Integer id) {
		try {
			User user = userService.selectByPrimaryKey(id);
			user.setDeleted(1);
			userService.updateByPrimaryKey(user);
			return Result.success();
		} catch (RuntimeException e) {
			log.error("UserController.del() throws exception:{}", e.getMessage());
		}
		return Result.fail();
	}
	
	@GetMapping("/reset")
	@ResponseBody
	public Result resetPassword(
			@RequestParam(required = true)
			Integer id) {
		// id
		try {
			User user = new User();
			user.setId(id);
			String password = "123456";
			SimpleHash simpleHash = new SimpleHash("MD5", password, ByteSource.Util.bytes(id + ""), 1);
			user.setPassword(simpleHash.toHex());
			userService.updateByPrimaryKeySelective(user);
			return new Result(true, "已经成功将用户密码重置成：123456");
		} catch (RuntimeException e) {
		}
		return Result.fail();
	}
	
	@PostMapping("/opt")
	@ResponseBody
	public Result opt(
			@RequestParam(value = "id", required = true)
			Integer uid, 
			@RequestParam(value = "rids", required = true)
			List<Integer> rids
			) {
		log.info("id:{}", uid);
		log.info("rids:{}", Arrays.toString(rids.toArray()));
		
		try {
			userService.insertUserWithRoles(uid, rids);
			return Result.success();
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
		
		return Result.fail();
	}
	
	@GetMapping("/roles")
	@ResponseBody
	public List<Integer> selectRolesByUid(
			@RequestParam(value = "id",  required = true)
			Integer uid
			) {
		List<Integer> rids = userService.selectRolesByUid(uid);
		return rids;
	}
	
	
}
